<?php
/**
 * CK框架 性能测试类
 * 用于测试函数/页面等占用的内存，时间 信息 
 * @author wujibing<283109896@qq.com>
 * @version   3.0
 * @category   CkFrameWork
 * @package  CkFrameWork
 * @subpackage lib
 */
class performanceTest
{
	/**
	 * 运行时间点
	 * @var int
	 */
	private static $_initTime;
	/**
	 * 判断一个函数运行所消耗的内存
	 * @param mixed $func 字符串的时候直接为函数名 数组的时候为 array(对象,'方法')
	 * @param array $args
	 * @return string
	 * <code>
	 * echo performanceTest::testMemory('printf',array('hello Word'));
	 * $myObject = new myObject();
	 * echo performanceTest::testMemory(array($myObject,'myFunc'),array('hello Word'));
	 * echo performanceTest::testMemory(array('staticClass','staticFunc'),array('hello Word'));
	 * </code>
	 */
	public static function testMemory($func,$args = array())
	{
		$startMemory = memory_get_usage();
		call_user_func_array($func, $args);
		$usedMemmory = memory_get_usage() - $startMemory;
		return sprintf('内存使用 %01.2f MB',$usedMemmory/1024/1024);
	}
	/**
	 * 判断一个函数的运行时间
	 * @param mixed $func 字符串的时候直接为函数名 数组的时候为 array(对象,'方法')
	 * @param array $args
	 * @return string
	 * <code>
	 * echo performanceTest::testTime('printf',array('hello Word'));
	 * $myObject = new myObject();
	 * echo performanceTest::testTime(array($myObject,'myFunc'),array('hello Word'));
	 * echo performanceTest::testTime(array('staticClass','staticFunc'),array('hello Word'));
	 * </code>
	 */
	public static function testTime($func,$args = array())
	{
		$startTime = microtime(true);
		call_user_func_array($func, $args);
		$usedTime = microtime(true) - $startTime;
		$usedTime = $usedTime * 1000;
		return '运行时间'.$usedTime.'ms';
	}
	/**
	 * 获取当前的运行内存
	 * @return string
	 * <code>
	 * echo performanceTest::getNowMemoryUsed();
	 * </code>
	 */
	public static function getNowMemoryUsed()
	{
		return sprintf('内存使用 %01.2f MB',memory_get_usage()/1024/1024);
	}
	/**
	 * 设置运行时间点
	 * <code>
	 * performanceTest::setInitTime();
	 * </code>
	 */
	public static function setInitTime()
	{
		self::$_initTime = microtime(true);
	}
	/**
	 * 获取上次运行时间点到现在的运行时间
	 * @return string
	 * <code>
	 * performanceTest::setInitTime();
	 * echo 1;
	 * //do something
	 * echo performanceTest::getRunTime();
	 * </code>
	 */
	public static function getRunTime()
	{
		$usedTime = microtime(true) - self::$_initTime;
		$usedTime = $usedTime * 1000;
		return '截止上次运行点，运行时间'.$usedTime.'ms';
	}
}